from django.shortcuts import render

# Create your views here.

import json
import re
from django.views import View
from django.http import JsonResponse,HttpResponse
from users.models import User, Address
from django import http
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate
from django.contrib.auth import logout
from meiduo_mall.utils.views import LoginRequiredMixin
from celery_tasks.email.tasks import send_verify_email


class UsernameCountView(View):
    def get(self, request, username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '访问出错'})
        return JsonResponse({'code': 0,
                            'errmsg': 'ok',
                            'count': count
                             })


class MobileCountView(View):
    def get(self,request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e :
            return JsonResponse({'code': 400, 'errmsg': '访问出错'})
        return JsonResponse({'code':0,'errmsg':'ok','count':count}

        )


class RegisterView(View):

    def post(self, request):
        '''接收参数, 保存到数据库'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        allow = dict.get('allow')
        sms_code_client = dict.get('sms_code')

        # 2.校验(整体)
        if not all([username, password, password2, mobile, allow, sms_code_client]):
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少必传参数'})

        # 3.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'username格式有误'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'password格式有误'})

        # 5.password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入不对'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'mobile格式有误'})
        # 7.allow检验
        if allow != True:
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'allow格式有误'})

        # 8.sms_code检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify_code')

        # 9.从redis中取值
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 10.判断该值是否存在
        if not sms_code_server:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '短信验证码以过期'})
        # 11.把redis中取得值和前端发的值对比
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '验证码不正确'})

        # 12.保存到数据库 (username password mobile)
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '保存到数据库出错'})
        # 实现状态保持
        login(request, user)

        # 13.拼接json返回
        return http.JsonResponse({'code': 0,
                                 'errmsg': 'ok'})


class LoginView(View):

    def post(self, request):
        # 1.接收json参数，获取每一个
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')


        # 2.总体检验，查看是否为空
        if not all([username,password]):
            return JsonResponse({"code":400,'errmsg':'缺少参数'})

        # 3.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code":400, "errmsg": '用户名格式错误'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({"code":400, "errmsg": '密码格式错误'})

        # 5.remembered检验
        if remembered:
            if not isinstance(remembered,bool):
                return JsonResponse({"code":400, "errmsg": "remembered不是bool类型"})

        # 6.登录认证(authenticate),获取用户
        user = authenticate(username=username,
                            password=password)

        # 7.判断该用户是否存在
        if not user:
            return JsonResponse({"code": 400, 'errmsg': "用户不存在"})

        # 8.状态保持
        login(request,user)

        # 9.判断是否需要记住用户
        if remembered != True:
            # 10.如果需要:设置sesion有效期:两周
            request.session.set_expiry(0)

        else:
            # 11.如果不需要:设置seesion有效期: 关闭浏览器立刻过期
            request.session.set_expiry(None)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        # 12.返回状态
        return response


class LogoutView(View):
    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response


# 给增加 Mixin 扩展类
class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""
    def get(self, request):
        """提供个人信息界面"""

        # 获取界面需要的数据,进行拼接
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        # 返回响应
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'info_data': info_data})


class EmailView(View):

    def put(self, request):
        '''保存email到数据库, 给邮箱发送邮件'''

        # 1.接收参数(json)
        dict = json.loads(request.body.decode())
        email = dict.get('email')

        # 2.检验参数:判断该参数是否有值
        if not email:
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.检验email的格式
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                 'errmsg': 'email格式不正确'})

        try:
            # 4.把前端发送的email赋值给当前用户
            request.user.email = email

            # 5.保存
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '保存邮箱失败'})

        # 6.TODO:给当前邮箱发送一封信
        verify_url = request.user.generate_access_token()
        send_verify_email.delay(email, verify_url)
        # 7.返回json结果
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})


class VerifyEmailView(View):

        def put(self, request):
            '''获取前端传入的token,解密,获取user,更改用户的email_active为true'''

            # 接收参数
            token = request.GET.get('token')

            # 校验参数：判断 token 是否为空和过期，提取 user
            if not token:
                return JsonResponse({'code': 400,
                                     'errmsg': 'token为空'})

            # 调用上面封装好的方法, 将 token 传入
            user = User.check_access_token(token)

            if not user:
                return JsonResponse({'code': 400,
                                     'errmsg': 'token错误'})

            # 修改 email_active 的值为 True
            try:
                user.email_active = True
                user.save()
            except Exception as e:
                return JsonResponse({'code': 400,
                                     'errmsg': '修改数据库出错'})

            # 返回邮箱验证结果
            return JsonResponse({'code': 0,
                                 'errmsg': 'ok'})


class CreateAddressView(View):
    def post(self, request):
        # 1.从mysqlZ中获取该用户的所有没有删除的地址个数
        try:
            count = Address.objects.filter(user=request.user, is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取地址数据出错'})

        # 2.判断该个数是否 >= 20, 如果是，返回
        if count >= 20:
            return JsonResponse({'code': 400,
                                 'errmsg': '添加地址上限'})
        # 3.接收参数(json)
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 4.总体检验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})
        # 5.单个检验mobile
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})
        # 6.tel
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})

        # 7.email
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        # 8.往Address表中增加地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        # 9.判断默认地址是否存在，如果不存在, 把刚刚增加的地址作为默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        # 10.拼接参数，返回
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '保存地址失败'})
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address': address_dict})


class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面"""
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code': 0,
                                  'errmsg': 'ok',
                                  'addresses': address_dict_list,
                                  'default_address_id': default_id})


class UpdateDestroyAddressView(View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '更新地址失败'})

        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0,
                             'errmsg': '更新地址成功',
                             'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return JsonResponse({'code': 0,
                            'errmsg': '删除地址成功'})


class DefaultAddressView(View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)
            # # 设置地址为默认地址
            request.user.default_address_id = address.id
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '设置默认地址失败'})

        # 响应设置默认地址结果
        return JsonResponse({'code': 0,
                            'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置地址标题成功'})


class ChangePasswordView(LoginRequiredMixin, View):
    """修改密码"""

    def put(self, request):
        """实现修改密码逻辑"""
        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400,
                                'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400,
                                'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,
                                'errmsg': '两次输入密码不一致'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '修改密码失败'})
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response





